var spaceNodeRef = findSpace("workspace://SpacesStore/2484a6e2-8809-410a-8f37-73f0a44cd901");
var projectId = "workspace://SpacesStore/98850837-290f-4c88-aaf0-0eaee3f07552";

if(spaceNodeRef == null) {
  logger.log("Destination space is null! Please check logs and configs (messias.post.config.xml).");
} else {
  var projectNodeRef = findSpace(projectId);
  var baselineNodeRef = createDestinationSpace(projectNodeRef.name, spaceNodeRef);

  logger.log("baselineNodeRef: "+baselineNodeRef.properties.name);
  logger.log("projectNodeRef: "+projectNodeRef.properties.name);

  var messias = createMessias(projectNodeRef, baselineNodeRef);

  if(!messias) {
     logger.log("Couldn't create messias baseline! Check logs");
  }
  logger.log("Messias baseline is here!");
}

function getLastVersion(nodeRef){

    if( nodeRef != null && nodeRef.versionHistory != null) {
        if(nodeRef.versionHistory.length > 0) {
            for(var i=0; i < nodeRef.versionHistory.length; i++) {
                logger.log("NodeRef version at ["+i+"] info:\n"+nodeRef.versionHistory[i]);
            }
            return nodeRef.versionHistory[0].node;
        } else {
            logger.log("No version file to "+nodeRef.properties.name+" or versionHistory has no versions so far.");
            return null;
        }
    } else {
        logger.log("Either nodeRef ("+nodeRef+") or versionControl ("+
        nodeRef.versionHistory+")is null");
        return null;
    }
}

function createLink(nodeRef, nodeRefDest) {
        var childNodeRefDest = findNode(nodeRefDest, nodeRef.properties.name);
        if(childNodeRefDest == null) {
            var nodeRefLink = [];
            var nodeName = nodeRef.name+"";
            var nodeRefName = nodeRef.nodeRef+"";
            var nodeTitle = nodeRef.title+"";
            var nodeDesc = nodeRef.description+"";

            nodeRefLink["cm:name"] = nodeName;
            nodeRefLink["cm:destination"] = nodeRefName;//"workspace://SpacesStore/122856a2-8420-4ae7-b642-1795415ba0cc";
            nodeRefLink["cm:title"] = nodeTitle;
            nodeRefLink["cm:description"] = nodeDesc;

            var linkNode = nodeRefDest.createNode(nodeName, "{http://www.alfresco.org/model/application/1.0}filelink", nodeRefLink);
            linkNode.save();
            logger.log("Link to "+nodeName+" successfully created in "+nodeRefDest.name+" space.");
            nodeRefDest.save();
        return true;
    } else {
        logger.log("Link to "+nodeRef.properties.name+" already exists! Info:"+childNodeRefDest);
        return false;
    }
}

function createDestinationSpace(spaceName, nodeRefDest) {
    var childNodeRef = findFolderNode(spaceName, nodeRefDest);
    if( childNodeRef == null) {
        logger.log(spaceName+" space created in the destination space:"+nodeRefDest.properties.name);
        var createdSpace = nodeRefDest.createFolder(spaceName);
        return createdSpace;
    } else {
            logger.log(spaceName+" space already exists in "+nodeRefDest.properties.name+" space! Returning first value:"+childNodeRef);
            return childNodeRef;
    }
}


function createMessias(nodeRefOrig, nodeRefDest) {

    if(nodeRefOrig == null || nodeRefDest == null) {
        logger.log("Either project nodeRef ("+nodeRefOrig+") or baseline nodeRef is ("+nodeRefDest+") null");
        return false;
    }

    if(nodeRefOrig.children == null || nodeRefOrig.children.length == 0) {
        logger.log("No childs... nothing to do!");
        return true;
    }

    logger.log("nodeRefOrig.isContainer:"+nodeRefOrig.isContainer);
    logger.log("nodeRefOrig.isDocument:"+nodeRefOrig.isDocument);

    for(var i=0; i < nodeRefOrig.children.length; i++) {
        var childNodeRef = nodeRefOrig.children[i];

        if(childNodeRef != null && childNodeRef.isContainer) {
            var childBaselineChildRef = createDestinationSpace(childNodeRef.name, nodeRefDest);
            if(childBaselineChildRef != null && childBaselineChildRef.isContainer) {
                var messiasResult = createMessias(childNodeRef, childBaselineChildRef);
                if(!messiasResult) {
                    logger.log("Couldn't create childs baseline spaces/links. Check logs!:"+childNodeRef.name+";"+childBaselineChildRef.name+"!");
                    return false;
                }
            } else {
                logger.log("Couldn't create baseline child space ("+childBaselineChildRef.properties.name+"). Check logs!");
                logger.log("Couldn't create baseline child file ("+childNodeRef.properties.name+"). Check logs!");
                return false;
            }
        } else {
            if(childNodeRef != null && childNodeRef.isDocument) {
                logger.log("childNodeRef name -> "+childNodeRef.properties.name);
                logger.log("childNodeRef nodeRef-> "+childNodeRef.properties.nodeRef);
                var childLink = createLink(getLastVersion(childNodeRef), nodeRefDest);
                if(childLink == null) {
                    logger.log("Couldn't create baseline child link ("+childNodeRef.properties.name+"). Check logs!");
                    return false;
                }
                logger.log("Baseline child link ("+childNodeRef.properties.name+") sucessfully created.");
             }
        }
    }//);
    return true;
}

function findNode(nodeRef, nodeRefName){
    logger.log("Finding Node: "+nodeRefName+" at "+nodeRef.name);
    for(var i =0; i< nodeRef.children.length ; i++) {
        var childNodeRef = nodeRef.children[i];
        if((childNodeRef.isDocument || childNodeRef.type == "{http://www.alfresco.org/model/application/1.0}filelink") && childNodeRef.properties.name == nodeRefName) {
            logger.log("Node Ref:"+childNodeRef.properties.name);
            return childNodeRef;
        }
    }
    logger.log("Couldn't found any node for given nodeRefId:"+nodeRefName);
    return null;
}

function findFolderNode(nodeRefName, nodeRef){
    logger.log("Finding Folder Node: "+nodeRefName+" at "+nodeRef.name);
    for(var i =0; i< nodeRef.children.length ; i++) {
        var childNodeRef = nodeRef.children[i];
        if(childNodeRef.isContainer && childNodeRef.properties.name == nodeRefName) {
            logger.log("Folder Node Ref:"+childNodeRef.properties.name);
            return childNodeRef;
        }
    }
    logger.log("Couldn't found any node for given nodeRefId:"+nodeRefName);
    return null;
}


function findSpace(nodeRefName) {
    logger.log("Finding space: "+nodeRefName);
    if(nodeRefName != null) {
        return search.findNode(nodeRefName);
     } else {
        logger.log("Space name shouldn't be null. Returning null");
        return null;
     }
}
